﻿using Barkod.Utility;
using Barkod.Utility.Grid;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraPivotGrid;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;

namespace Barkod
{
    public partial class XForm : DevExpress.XtraEditors.XtraForm
    {
        public static int WhoAmI = -1;
        public int MyDept = -1;


        public Image notready = Properties.Resources.NotReadySmall;
        string adet = "Count: ";
        string toplam = "Sum: ";

        public virtual void RefreshData()
        {
        }

        public XForm()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;

        }

        public void ExecQuery(string SP, params object[] prm)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                AppSession.DataManager.ExecuteNonQuery(SP, prm);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        public void SetGridCaption(GridView gv, string caption)
        {
            gv.OptionsView.ShowViewCaption = true;
            gv.Appearance.ViewCaption.TextOptions.HAlignment = HorzAlignment.Near;
            gv.ViewCaption = caption;
        }





        public void InitGridView(GridView gridview, BindingSource bs, bool initialized = false)
        {
            try
            {

                gridview.BeginUpdate();
                gridview.Columns.Clear();
                if (bs != null)
                {
                    gridview.GridControl.DataSource = null;
                    gridview.GridControl.DataSource = bs;
                    gridview.PopulateColumns();
                }
                if (gridview.ViewCaption == string.Empty)
                    gridview.ViewCaption = gridview.Name;

                bool containsProduct = gridview.Columns.Contains(gridview.Columns["ProductId"]);

                foreach (GridColumn col in gridview.Columns)
                {
                    if (col.FieldName != bs.DataMember + "Id")
                    {
                        //MapGridColumn(col);                        
                    }
                    else
                    {
                        col.OptionsColumn.AllowEdit = false;
                        col.AppearanceCell.BackColor = System.Drawing.Color.LightYellow;
                    }

                    if (col.ColumnType == Type.GetType("System.Boolean"))
                    {
                        RepositoryItemCheckEdit ri = new RepositoryItemCheckEdit();
                        ri.AllowGrayed = false;
                        col.ColumnEdit = ri;
                    }
                    else if (col.ColumnType == typeof(DateTime))
                    {
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.DateSmart;
                        col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                        col.OptionsFilter.ImmediateUpdateAutoFilter = true;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnCheck = DevExpress.Utils.DefaultBoolean.True;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnDateChange = DevExpress.Utils.DefaultBoolean.True;
                    }
                    else if (col.ColumnEdit is RepositoryItemGridLookUpEdit)
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.CheckedList;
                }
                if (containsProduct)
                {
                    GridColumn colPhoto = new GridColumn();
                    if (gridview.GetType() == typeof(BandedGridView))
                        colPhoto = new BandedGridColumn();

                    colPhoto.FieldName = "Scan";
                    gridview.Columns.Add(colPhoto);

                    colPhoto.ColumnEdit = new RepositoryItemPictureEdit();
                    colPhoto.UnboundType = DevExpress.Data.UnboundColumnType.Object;

                    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).SizeMode = PictureSizeMode.Clip;
                    (colPhoto.ColumnEdit as RepositoryItemPictureEdit).NullText = " ";
                    CenterGridColumn(colPhoto);


                    List<string> visibleColumnNames = new List<string>();
                    foreach (GridColumn gc in gridview.Columns)
                        if (gc.Visible)
                            visibleColumnNames.Add(gc.FieldName);

                    foreach (GridColumn gc in gridview.Columns)
                        gc.VisibleIndex = -1;

                    int k = -1;
                    if (gridview.GetType() == typeof(BandedGridView))
                        k++;

                    if (visibleColumnNames.Contains("ProductId"))
                    {
                        int scanIndex = visibleColumnNames.IndexOf("ProductId");
                        visibleColumnNames.Insert(scanIndex, "Scan");
                    }
                    else if (gridview.Columns["Scan"] != null)
                        visibleColumnNames.Insert(0, "Scan");

                    foreach (string colName in visibleColumnNames)
                    {
                        GridColumn col = gridview.Columns[colName];
                        k++;
                        col.VisibleIndex = k;
                    }

                    gridview.CalcRowHeight -= new RowHeightEventHandler(gridview_CalcRowHeight);
                    gridview.CalcRowHeight += new RowHeightEventHandler(gridview_CalcRowHeight);

                    gridview.CustomDrawCell -= new RowCellCustomDrawEventHandler(XForm_CustomDrawCell);
                    gridview.CustomDrawCell += new RowCellCustomDrawEventHandler(XForm_CustomDrawCell);
                }

                gridview.BestFitMaxRowCount = 200;
                gridview.GridControl.ShowOnlyPredefinedDetails = true;
                gridview.HorzScrollStep = 50;
                gridview.NewItemRowText = "Click to add new row";
                gridview.OptionsBehavior.CopyToClipboardWithColumnHeaders = false;
                gridview.OptionsBehavior.ImmediateUpdateRowPosition = false;
                gridview.OptionsBehavior.KeepFocusedRowOnUpdate = true;
                gridview.OptionsFilter.AllowColumnMRUFilterList = true;
                gridview.OptionsFilter.ShowAllTableValuesInCheckedFilterPopup = false;
                gridview.OptionsFilter.ShowAllTableValuesInFilterPopup = false;
                gridview.OptionsHint.ShowColumnHeaderHints = true;
                gridview.OptionsMenu.EnableColumnMenu = true;
                gridview.OptionsMenu.ShowDateTimeGroupIntervalItems = true;
                gridview.OptionsNavigation.UseOfficePageNavigation = true;
                gridview.OptionsSelection.MultiSelect = true;
                gridview.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
                gridview.OptionsView.ColumnAutoWidth = false;
                gridview.OptionsView.RowAutoHeight = true;
                gridview.OptionsView.ShowAutoFilterRow = true;
                gridview.OptionsView.ShowDetailButtons = false;
                gridview.OptionsView.ShowGroupPanel = false;
                gridview.ViewCaption = gridview.ViewCaption.Replace("gv", string.Empty);

                foreach (GridColumn gc in gridview.Columns)
                {
                    string colName = gc.FieldName.ToLower();
                    if (colName == "modifiedon" || colName == "ts" || colName == "deleted")
                        gc.Visible = false;
                    else
                        gc.Visible = true;
                }
                GridManager.GetManager(gridview);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                gridview.EndUpdate();
            }
        }


        public PivotGridField AddNewField(PivotGridControl pgc, string FieldName, PivotArea pa)
        {
            PivotGridField fd = new PivotGridField();
            fd.FieldName = fd.Caption = FieldName;
            fd.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            fd.CellFormat.FormatString = "#,###.##";
            pgc.Fields.Add(fd);
            fd.SetAreaPosition(pa, 0);

            fd.Name = "_" + FieldName;
            return fd;
        }

        public enum AcKapa
        {
            Expand = 0,
            Collapse
        }

        public void ExpandCollapse(SplitContainerControl sc, AcKapa action)
        {
            FieldInfo fi = typeof(SplitContainerControl).GetField("containerInfo", BindingFlags.NonPublic | BindingFlags.Instance);
            DevExpress.XtraEditors.Drawing.SplitContainerViewInfo vInfo = fi.GetValue(sc) as DevExpress.XtraEditors.Drawing.SplitContainerViewInfo;
            if ((vInfo.Splitter.IsCollapsed) ^ (action == AcKapa.Collapse))
                vInfo.Splitter.DoExpandCollapseOnClick();
        }

        void XForm_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle > -1)
                if ((e.Column.FieldName == "Scan" || e.Column.FieldName == "PhotoMikro") &&
                    (e.CellValue == DBNull.Value || e.CellValue == null))
                {
                    //e.DisplayText = "X";
                    e.Graphics.DrawImageUnscaled(notready, e.Bounds.X + (e.Bounds.Width / 2 - 16), e.Bounds.Y);
                    e.Handled = true;
                }
        }

        void gridview_CalcRowHeight(object sender, RowHeightEventArgs e)
        {
            if (e.RowHandle > -1)
                if (e.RowHeight < notready.Height)
                    e.RowHeight = notready.Height;
        }


        public void CenterGridColumn(GridColumn col)
        {
            col.AppearanceCell.Options.UseTextOptions = true;
            col.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
        }
        public static void SetSplitterPosition(SplitContainerControl scc)
        {
            scc.SplitterPosition = (scc.Horizontal ? scc.Width : scc.Height) / 2;
        }

        public virtual void MySizeChanged(object sender, EventArgs e)
        {
            SplitContainerControl scc = ((SplitContainerControl)sender);
            //scc.SizeChanged -= sizeChanged;
            //SetSplitterPosition(sender as SplitContainerControl);
            scc.SplitterPosition = (scc.Horizontal ? scc.Width : scc.Height) / 2;
        }

        public List<BindingSource> sources;
        public void EndEdits()
        {
            this.Validate();
            if (sources != null)
                foreach (BindingSource bs in sources)
                    bs.EndEdit();
        }




        private void XForm_Load(object sender, EventArgs e)
        {
        }

        public virtual void cmbYil_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}